package com.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;

import com.sun.org.apache.commons.collections.CollectionUtils;

/**
 * 文 件 名: FileTool.java 版 权: 深圳埃思欧纳信息咨询有限公司版权所有. YYYY-YYYY, All rights reserved
 * 描 述: <描述> 修 改 人: jeray.wu 修改时间: 2010-8-24 上午10:23:35 跟踪单号: <跟踪单号> 修改单号:
 * <修改单号> 修改内容: <修改内容>
 */
public class FileTool
{

	/**
	 * 复制文件夹及文件夹下的文件到另一文件夹目录下
	 * <功能详细描述>
	 * @param paramString1
	 * @param paramString2
	 * @throws IOException
	 * 
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	public void copyDirectiory(String paramString1, String paramString2) throws IOException
  {
    if (!(new File(paramString2).exists()))
      new File(paramString2).mkdirs();
    File[] arrayOfFile = new File(paramString1).listFiles();
    for (int i = 0; i < arrayOfFile.length; ++i)
    {
      System.out.println(arrayOfFile[i].getName());
      if (arrayOfFile[i].isFile())
      {
        FileInputStream localFileInputStream = new FileInputStream(arrayOfFile[i]);
        FileOutputStream localFileOutputStream = new FileOutputStream(paramString2 + "/" + arrayOfFile[i].getName());
        byte[] arrayOfByte = new byte[5120];
        int j;
        while ((j = localFileInputStream.read(arrayOfByte)) != -1)
        {
        localFileOutputStream.write(arrayOfByte, 0, j); }
        localFileOutputStream.flush();
        localFileOutputStream.close();
        localFileInputStream.close();
      }
      if (arrayOfFile[i].isDirectory())
        copyDirectiory(paramString1 + "/" + arrayOfFile[i].getName(), paramString2 + "/" + arrayOfFile[i].getName());
    }
  }
    /**
     * 读取文件夹文件列表
     * @param dirname
     * @return [参数说明]
     * 
     * @return List [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static List<String> getFiles(String dirname)
    {
        File dir = new File(dirname);
        File[] files = dir.listFiles();
        List<String> file_names = new ArrayList<String>();
        for (int i = 0; i < files.length; i++)
        {
            if (files[i].isDirectory())
            {// 判断是否是目录
                // file_names.add(files[i].getName() + "=>它是一个文件夹");
            }
            if (files[i].isHidden())
            {// 判断是否是隐藏文件
                // file_names.add(files[i].getName() + "=>它是一个隐藏文");
            }
            if (files[i].isFile() && (!files[i].isHidden()))
            {// 判断是否是文件并不能是隐藏文件
                file_names.add(files[i].getName());
            }
        }
        return file_names;
    }

    /**
     * 读文件到list中
     * @param path
     * @return List
     * @roseuid 456BE5C901DA
     */
    public static List<String> fileToList(String path)
    {
        List<String> fileList = new ArrayList<String>();
        BufferedReader myBufferedReader = null;
        String myString = null;
        FileReader fr = null;
        try
        {
            fr = new FileReader(path);
            myBufferedReader = new BufferedReader(fr);
            while ((myString = myBufferedReader.readLine()) != null)
            {
                if (!myString.equals(""))
                    fileList.add(myString);
            }
            if (myString != null)
            {
                myString = null;
            }
            if (fr != null)
            {
                fr.close();
                fr = null;
            }
            if (myBufferedReader != null)
            {
                myBufferedReader.close();
                myBufferedReader = null;
            }
            return fileList;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
        finally
        {
            try
            {
                if (myString != null)
                {
                    myString = null;
                }
                if (fr != null)
                {
                    fr.close();
                    fr = null;
                }
                if (myBufferedReader != null)
                {
                    myBufferedReader.close();
                    myBufferedReader = null;
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 把list中的string写入文件中
     * @param path
     * @param list
     * @return boolean
     * @roseuid 456BE6370124
     */
    public static boolean listToFile(String path, List<String> list)
    {
        if (path == null)
        {
            System.out.println("path is null");
            return false;
        }

        File file = new File(path);
        if (!file.getParentFile().exists())
        {
            file.getParentFile().mkdirs();
        }

        PrintWriter pw = null;
        try
        {
            pw = new PrintWriter(new BufferedWriter(new FileWriter(path)));
            for (String line : list)
            {
                pw.println(line);
            }
            pw.flush();
            return true;
        }
        catch (IOException e)
        {
            // e.printStackTrace();
            return false;
        }
        finally
        {
            try
            {
                pw.close();
            }
            catch (Exception e)
            {
            }
        }

    }

    /**
     * 读取文件内容
     * 
     * @param filePathAndName String 如 c:\\1.txt 绝对路径
     * @return boolean
     */
    public static List<String> readFile(String filePathAndName)
    {
        List<String> fileList = new ArrayList<String>();
        try
        {
            File f = new File(filePathAndName);
            if (f.isFile() && f.exists())
            {
                InputStreamReader read = new InputStreamReader(new FileInputStream(f), "GBK");
                BufferedReader reader = new BufferedReader(read);
                String line;
                while ((line = reader.readLine()) != null)
                {
                    fileList.add(line);
//                    fileContent += line;
                }
                read.close();
            }
        }
        catch (Exception e)
        {
            System.out.println("读取文件内容操作出错");
            e.printStackTrace();
        }
        return fileList;
    }

    /**
     * 写文件内容
     * <功能详细描述>
     * @param filePathAndName
     * @param list
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static void writeFile(String filePathAndName,  List<String> list)
    {
        try
        {
            File f = new File(filePathAndName);
            if (!f.getParentFile().exists())
            {
                f.getParentFile().mkdirs();
            }
            if (!f.exists())
            {
                f.createNewFile();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
            BufferedWriter writer = new BufferedWriter(write);
            // PrintWriter writer = new PrintWriter(new BufferedWriter(new
            // FileWriter(filePathAndName)));
            // PrintWriter writer = new PrintWriter(new
            // FileWriter(filePathAndName));
            for (String line : list)
            {
                writer.write(line+"\r\n");
            }
            
            writer.close();
        }
        catch (Exception e)
        {
            System.out.println("写文件内容操作出错");
            e.printStackTrace();
        }
    }
    
    public static String randomRename(String fileName, String dir) {
		String[] split = fileName.split("\\.");// 将文件名已.的形式拆分
		String extendFile = "." + split[split.length - 1].toLowerCase(); // 获文件的有效后缀
		Random random = new Random();
		int add = random.nextInt(1000000); // 产生随机数10000以内
		String ret = add + extendFile;
		while (isFileExist(ret, dir)) {
			add = random.nextInt(1000000);
			ret = fileName + add + extendFile;
		}
		File file = new File(dir + fileName);
		File reFile = new File(dir + ret);
		file.renameTo(reFile);
		String name = reFile.getName();
		file = null;
		reFile = null;
		return name;
	}

	/**
	 * 删除文件
	 * 
	 * @param filePathAndName
	 *          String 文件路径及名称 如c:/fqf.txt
	 * @param fileContent
	 *          String
	 * @return boolean
	 */
	public static boolean delFile(String filePathAndName) {
		File myDelFile = new java.io.File(filePathAndName);
		if (!myDelFile.exists()) {
			return true;
		}
		return myDelFile.delete();
	}

	/**
	 * 根据路径创建一系列的目录
	 * 
	 * @param path
	 */
	public static void mkDirectory(String path) {
		File file;
		try {
			file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			file = null;
		}
	}

	/**
	 * 将对象数组的每一个元素分别添加到指定集合中,调用Apache commons collections 中的方法
	 * 
	 * @param collection
	 *          目标集合对象
	 * @param arr
	 *          对象数组
	 */
	public static void addToCollection(Collection collection, Object[] arr) {
		if (null != collection && null != arr) {
			CollectionUtils.addAll(collection, arr);
		}
	}

	/**
	 * 将字符串已多个分隔符拆分为数组,调用Apache commons lang 中的方法
	 * 
	 * <pre>
	 *    Example:
	 *     String[] arr = StringUtils.split("a b,c d,e-f", " ,");
	 *     System.out.println(arr.length);//输出6
	 * </pre>
	 * 
	 * @param str
	 *          目标字符串
	 * @param separatorChars
	 *          分隔符字符串
	 * @return 字符串数组
	 */
	public static String[] split(String str, String separatorChars) {
		return StringUtils.split(str, separatorChars);
	}
	/**
	 * 判断文件是否存在
	 * 
	 * @param fileName
	 * @param dir
	 * @return
	 */
	public static boolean isFileExist(String fileName, String dir) {
		File files = new File(dir + fileName);
		return (files.exists()) ? true : false;
	}

	/**
	 * 获得随机文件名,保证在同一个文件夹下不同名
	 * 
	 * @param fileName
	 * @param dir
	 * @return
	 */
	public static String getRandomName(String fileName, String dir) {
		String[] split = fileName.split("\\.");// 将文件名已.的形式拆分
		String extendFile = "." + split[split.length - 1].toLowerCase(); // 获文件的有效后缀

		Random random = new Random();
		int add = random.nextInt(1000000); // 产生随机数10000以内
		String ret = add + extendFile;
		while (isFileExist(ret, dir)) {
			add = random.nextInt(1000000);
			ret = fileName + add + extendFile;
		}
		return ret;
	}
	
	/**
	 * 判断文件类型是否是合法的,就是判断allowTypes中是否包含contentType
	 * 
	 * @param contentType
	 *          文件类型
	 * @param allowTypes
	 *          文件类型列表
	 * @return 是否合法
	 */
	public static boolean isValid(String contentType, String[] allowTypes) {
		if (null == contentType || "".equals(contentType)) {
			return false;
		}
		for (int i = 0; i < allowTypes.length; i++) {
			String type = allowTypes[i];
			if (contentType.equals(type)) {
				return true;
			}
		}
		return false;
	}
    
    /**
     * 复制文件,无乱码
     * @param srcPath 原文件路径
     * @param destPath 目的文件路径
     */
    public static void copyForFile(String srcPath,String destPath){
     BufferedInputStream br = null;
     BufferedOutputStream bw = null;
     try {
     br =new BufferedInputStream(new FileInputStream(srcPath));
     bw = new BufferedOutputStream(new FileOutputStream(destPath));
     byte[] b = new byte[1024];
     int size = -1;
     //循环读
     while ((size = br.read(b)) != -1) {
       bw.write(b, 0, size);
     }
     } catch (FileNotFoundException e) {
      e.printStackTrace();
     } catch (IOException e) {
      e.printStackTrace();
     }finally{
      try {
       if(br != null){
        br.close();
       }
       if(bw != null){
        bw.close();
       }
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    }
    /**
     * 读文件,无乱码
     * @param srcFile 原文件
     */
    public static void readerForFile(String srcFile){
     BufferedReader br = null;
     try {
       br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile),"gbk"));
       //一行一行的读
      String Line;
      while((Line = br.readLine()) != null){
       System.out.println(Line);
      }
     } catch (IOException e) {
      e.printStackTrace();
     } finally {
       try {
        if (br != null) {
        br.close();
        }
       } catch (IOException e) {
        e.printStackTrace();
       }
     }
    }
    /**
     * 读取url,无乱码
     * @param urlStr url,需加http://
     */
    public static void readerForURLToFile(String urlStr){
     BufferedReader br = null;
     StringBuffer sb = null;
     try {
      URL url = new URL(urlStr);
      br = new BufferedReader(new InputStreamReader(url.openStream(),"gbk"));
      sb = new StringBuffer();
      String str = null;
      while((str = br.readLine())!= null){
       sb.append(str).append("\r\n");
      }
      System.out.println(sb);
     } catch (MalformedURLException e) {
      e.printStackTrace();
     } catch (IOException e) {
      e.printStackTrace();
     }finally{
      try {
       if(br != null){
        br.close();
       }
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    }
    /**
     * 写文件,追加模式,无乱码
     * @param srcFile 原文件
     */
    public static void writerForFileAddModel(String srcFile){
     FileWriter fw = null;
     try {
     fw = new FileWriter(srcFile,true);
     fw.write("\r\n");
     fw.write("sjkd39840823094你好啊啊啊啊啊啊 ");
     } catch (FileNotFoundException e) {
      e.printStackTrace();
     } catch (IOException e) {
      e.printStackTrace();
     } finally{
      try {
       if(fw != null){
        fw.close();
       }
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    }
    /**
     * 写文件,无乱码,以数组形式写入
     * @param srcFile 原文件
     * @param arg0 
     */
    public static void writerForFile(String srcFile,String []arg0){
     PrintWriter pw = null;
     try {
      pw = new PrintWriter(new FileWriter(srcFile));
      for (int i = 0; i < arg0.length; i++) {
       pw.write(arg0[i]);
       pw.println();
         }
     } catch (IOException e) {
      e.printStackTrace();
     }finally{
      if(pw != null){
       pw.close();
      }
       
     }
     }
    /**
     * 获取所有文件夹下所有文件名字
     * @param listFile 文件
     */
    public static void getALLFileNameForFolder(String listFile){
           File file = new File(listFile);   
           System.out.println("是目录吗？" + file.isDirectory());
     System.out.println("是文件吗？" + file.isFile());
     System.out.println("最后修改时间:" + new Date(file.lastModified()));
     System.out.println("路径:" + file.getPath());
     System.out.println("绝对路径:" + file.getAbsolutePath()); 
     System.out.println("文件大小:" + file.length() + "字节");
     System.out.println("是否可写:" + file.canWrite());
           File[] array = file.listFiles();    
           for(int i=0;i<array.length;i++){    
               if(array[i].isFile()){    
                   System.out.println("文件名:" + array[i].getName()+
                        "文件路径:"+array[i].getParent()+
                         "文件全路径:"+array[i].getPath());
               }   
           }
    }
    /**
     * 根据名字删除文件
     * @param fileName 文件名路径
     * @return
     */
    public static boolean deleteForFileName(String fileDir){
     boolean flag = false;
     File file = new File(fileDir);
     if(file.isFile() && file.exists()){
      file.delete();
      flag = true;
     }
     return flag;
    }
    /**
     * 重命名文件
     * @param newFileName 文件名
     */
    public static void renameForFileName(String newFileName){
     File afile = new File(newFileName);
     File bfile = new File("c:/1.txt");
     afile.renameTo(bfile);
    }
    /**
     * 删除文件夹,包括子文件夹,文件.包括隐藏文件(效率????)
     * @param fileDir 文件夹路径
     */
    public static void deleteForALLFile(File fileDir){
     if(fileDir.exists()){ //是否存在
      if(fileDir.isDirectory()){//是否是目录
       File files[] = fileDir.listFiles();
           for(int i=0;i<files.length;i++){ 
              deleteForALLFile(files[i]); 
        }
      }else{
       fileDir.delete();
      }
     }else{
      System.out.println("不存在目录："+fileDir.getPath());
     }
    }
    /**
     *  根据后缀名删除文件 ?
     * @param file 文件名 
     */
    public static void deleteForFileSuffix(String fileDir){
     // 删除单一文件
     String aFile = fileDir;
     //根据字符返回最后一处出现的索引
     int suffixSymbol = aFile.lastIndexOf(".");
     String suffix =aFile.substring(suffixSymbol+1);
     System.out.println(suffix);
     File file = new File(aFile);
     if(suffix.equalsIgnoreCase("txt")){
      file.delete();
     }
    }   
    /**
     * 计算文件个数
     * @param fileDir 文件
     */
    public static void numForFile(String fileDir){
     File file = new File(fileDir);
     File []arrayFile =file.listFiles();
     System.out.println(arrayFile.length);
    }

    @SuppressWarnings("static-access")
	public List<String> getDirPath()
    {
//       String dirPath = "F:\\mv\\2009070201";
       String dirPath = "F:\\常识必备\\消除系统LJ.txt";
//       List<String> list = this.getFiles(dirPath);
      List<String> list = this.fileToList(dirPath);
	   return list;
    }
    
    public static void main(String[] args)throws Exception
    {
 	    new FileTool().copyDirectiory("E:\\book文档","E:\\bookTest");
    }
//    public static void main(String[] ar)
//    {
//    	FileTool fileList = new FileTool();
//    	List<String> list = fileList.getDirPath();
// //   	fileList.fileToList("F:\\常识必备\\test.txt");
//    	for(int i=0;i<list.size();i++)
//    	{
//    		String fileName = list.get(i);
//    		System.out.print(fileName);
//    	}
//    	
//        //copyForFile("c:\\你.txt","d:\\好.txt");
//        //readerForFile("c:\\你.txt");
//        writerForFileAddModel("c:\\你.txt");
//        /*
//        String str[] = new String[3];
//        str[0]="你=好";
//        str[1]="0=1";
//        str[2]="0=1";
//        writerForFile("c:\\你.txt",str);
//        */
//        //deleteForFileName("src/test.properties");
//        //getALLFileNameForFolder("C:/Youku/db");
//      //  File  file= new File("c://1");
//      //  deleteForALLFile(file);
//        //deleteForFileSuffix("F:/1");
//        //numForFile("F:/1");
//        //renameForFileName("c:/你.txt");
//      //  readerForURLToFile("http://www.qq.com");
//       
//    }
}
